package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(required = false , defaultValue = "1") Integer page,
                  @RequestParam(required = false , defaultValue = "10")Integer pageSize){

        log.debug("分页查询开始了....");

        //构建分页信息
        Page<Category> pageInfo = new Page<>(page,pageSize);

        //根据sort字段排序
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);

        //调用分页查询
        categoryService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 添加分类操作
     * @param category
     * @return
     */
    @PostMapping
    public R save(@RequestBody Category category){
        categoryService.save(category);
        return R.success();
    }

    /**
     * 根据ID删除（逻辑外键）
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long  id){
        categoryService.deleteById(id);
        return R.success();
    }

    /**
     * 修改菜品信息时，数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Category> selectById(@PathVariable Long id){
        Category category = categoryService.getById(id);
        if (category == null){
            return R.error("系统繁忙,请稍后再试");
        }
        return R.success(category);
    }

    /**
     * 修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){
        boolean b = categoryService.updateById(category);
        if (!b){
            return R.error("系统繁忙,请稍后再试");
        }

        return R.success();
    }

    /**
     * 添加菜品时，需要获取所有菜品分类信息
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(type!=null,Category::getType,type);
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categories = categoryService.list(categoryLambdaQueryWrapper);

        return R.success(categories);
    }
}
